package com.xie.backend.consumer;

import com.alibaba.fastjson.JSON;
import com.xie.backend.consumer.utils.JwtAuthentication;
import com.xie.backend.mapper.UserMapper;
import com.xie.backend.consumer.utils.Chat;
import com.xie.backend.consumer.utils.Msg;
import com.xie.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @作者：xie
 * @时间：2022/11/25 10:16
 */
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketTest {

    private User user;

//    public final static ConcurrentHashMap<Integer, WebSocketTest> users = new ConcurrentHashMap<>();
    private Session session = null;
    public static UserMapper userMapper;
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        WebSocketTest.userMapper = userMapper;
    }


    /**
     * 存放所有在线的客户端
     */
    private static Map<Integer, Session> clients = new ConcurrentHashMap<>();
//    private String userId;

    @OnOpen
    public void onOpen(Session session,  @PathParam("token") String token) throws IOException {
        // 建立连接
        this.session = session;
        Integer userId = JwtAuthentication.getUserId(token);
        this.user = userMapper.selectById(userId);

        if (this.user != null) {
            clients.put(this.user.getId(),this.session);
            Chat chat = new Chat();
            chat.setUserMsg(new Msg(false,"有新人加入聊天",true));
            sendAll(chat.getUserMsg().toString());
            System.out.println("打开了一个连接");
            System.out.println("userId:"+userId);
        } else {
            this.session.close();
        }





    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("有用户断开了");
        Chat chat = new Chat();
        chat.setUserMsg(new Msg(false,"有用户断开聊天",true));
        sendAll(chat.toString());
        if (this.user != null) {
            clients.remove(this.user.getId());}
        //将掉线的用户移除在线的组里
//        clients.remove(userId);
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        //throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("服务端收到客户端发来的消息:"+message);
        Chat chat = JSON.parseObject(message, Chat.class);
        chat.getUserMsg().setSend(false);
        this.sendAll(chat.toString());
    }

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendAll(String message) {
        for (Map.Entry<Integer, Session> sessionEntry : clients.entrySet()) {
            if (!sessionEntry.getKey().equals(this.user.getId())){
                sessionEntry.getValue().getAsyncRemote().sendText(message);
                System.out.println("服务端将客户端发来的消息发送出去:"+message);

            }
        }
    }
}
